import pandas as pd
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.filterwarnings('ignore')

# 准备数据
data = {
    'Year': [ 2019, 2020, 2021, 2022, 2023],
    'Cats': [ 4412, 4862, 5806, 6536, 6980],  # 宠物猫数量（万只）
    'Dogs': [ 5503, 5222, 5429, 5119, 5175],  # 宠物狗数量（万只）
    'GDP_Per_Capita': [ 98.65, 101.36, 114.92, 120.47, 126.06],  # 人均GDP（万亿）
    'Urbanization_Rate': [0.6060, 0.6389, 0.6472, 0.6522, 0.6616],  # 城镇化率
    'Total_Population': [ 14.0005, 14.435, 14.126, 14.1175, 14.0967],  # 总人口（百万人）
    'Cat_Market_Size': [ 780, 884, 1060, 1231, 1305],  # 猫的市场规模（亿元）
    'Dog_Market_Size': [ 1244, 1180, 1430, 1475, 1488],  # 狗的市场规模（亿元）
    'Cat_Annual_Consumption': [ 1768, 1818, 1826, 1883, 1870],  # 一只猫年均消费金额 （元）
    'Dog_Annual_Consumption': [2261, 2262, 2634, 2282, 2875],  # 一只狗年均消费金额（元）
    'China_pet_medical_market_size':[405,400,675,640,700]     #中国宠物医疗市场规模
    # 可以添加更多宠物类型的数据
}
# 创建数据框
df = pd.DataFrame(data)
# 特征数量和目标变量
# 对于宠物猫模型的构建
x_cat = df[['Year', 'GDP_Per_Capita', 'Urbanization_Rate', 'Total_Population',
           'Cat_Market_Size', 'Cat_Annual_Consumption','China_pet_medical_market_size']]
y_cat = df['Cats']

# 对于宠物狗的模型构建
x_dog = df[['Year', 'GDP_Per_Capita', 'Urbanization_Rate', 'Total_Population',
           'Dog_Market_Size', 'Dog_Annual_Consumption','China_pet_medical_market_size']]
y_dog = df['Dogs']

# 设置随机森林模型的超参数网格
param_grid = {
    'n_estimators': [50, 100, 200],        # 森林的树木数量
    'max_depth': [5, 10, 15, None],         # 树的最大深度
    'min_samples_split': [2, 5, 10],        # 结点分割的最小样本数
    'min_samples_leaf': [1, 2, 4],          # 叶子结点的最小样本数
    'max_features': ['auto', 'sqrt', 'log2']    # 每颗树考虑的最大特征数
}
# 创建随机森林模型
cat_model = RandomForestRegressor(random_state=42)
dog_model = RandomForestRegressor(random_state=42)
# 使用GridSearchCV进行超参数优化宠物猫模型
cat_grid_search = GridSearchCV(estimator=cat_model, param_grid=param_grid,
                               cv=3, scoring='neg_mean_squared_error', verbose=0, n_jobs=-1)
cat_grid_search.fit(x_cat, y_cat)
best_cat_model = cat_grid_search.best_estimator_

# 使用GridSearchCV进行超参数优化宠物狗模型
dog_grid_search = GridSearchCV(estimator=dog_model, param_grid=param_grid,
                               cv=3, scoring='neg_mean_squared_error', verbose=0, n_jobs=-1)
dog_grid_search.fit(x_dog, y_dog)
best_dog_model = dog_grid_search.best_estimator_

# 输出最佳超参数
print("\n最佳参数-宠物猫模型：")
print(cat_grid_search.best_params_)
print("\n最佳超参数-宠物狗模型：")
print(dog_grid_search.best_params_)

# 预测未来2024年至2026年的趋势
future_years = [2024, 2025, 2026]

# 使用线性代数回归预测未来值


def predict_future(df, future_data, years):
    prediction = {}
    for feature in future_data:
        x = df[['Year']]
        y = df[feature]
        model = LinearRegression()
        model.fit(x, y)
        future_values = model.predict(pd.DataFrame({'Year': years}))
        prediction[feature] = future_values
    return prediction

# 预测所需要的数据


cat_future_data = ['GDP_Per_Capita', 'Urbanization_Rate',
                   'Total_Population', 'Cat_Market_Size', 'Cat_Annual_Consumption','China_pet_medical_market_size']
dog_future_data = ['GDP_Per_Capita', 'Urbanization_Rate',
                   'Total_Population', 'Dog_Market_Size', 'Dog_Annual_Consumption','China_pet_medical_market_size']

cat_future_features = predict_future(df, cat_future_data, future_years)
dog_future_features = predict_future(df, dog_future_data, future_years)

# 创建未来模型预测的数据框
future_cat_df = pd.DataFrame({
    'Year': future_years,
    'GDP_Per_Capita': cat_future_features['GDP_Per_Capita'],
    'Urbanization_Rate': cat_future_features['Urbanization_Rate'],
    'Total_Population': cat_future_features['Total_Population'],
    'Cat_Market_Size': cat_future_features['Cat_Market_Size'],
    'Cat_Annual_Consumption': cat_future_features['Cat_Annual_Consumption'],
    'China_pet_medical_market_size': cat_future_features['China_pet_medical_market_size']
})

future_dog_df = pd.DataFrame({
    'Year': future_years,
    'GDP_Per_Capita': dog_future_features['GDP_Per_Capita'],
    'Urbanization_Rate': dog_future_features['Urbanization_Rate'],
    'Total_Population': dog_future_features['Total_Population'],
    'Dog_Market_Size': dog_future_features['Dog_Market_Size'],
    'Dog_Annual_Consumption': dog_future_features['Dog_Annual_Consumption'],
    'China_pet_medical_market_size':dog_future_features['China_pet_medical_market_size']
})

# 使用最佳模型进行预测
cat_predictions = best_cat_model.predict(future_cat_df)
dog_predictions = best_dog_model.predict(future_dog_df)
# 评估模型性能
cat_train_pred = best_cat_model.predict(x_cat)
dog_train_pred = best_dog_model.predict(x_dog)

cat_mse = mean_squared_error(y_cat, cat_train_pred)
cat_mae = mean_absolute_error(y_cat, cat_train_pred)
cat_r2 = r2_score(y_cat, cat_train_pred)

dog_mse = mean_squared_error(y_dog, dog_train_pred)
dog_mae = mean_absolute_error(y_dog, dog_train_pred)
dog_r2 = r2_score(y_dog, dog_train_pred)

print("\n模型评估指标：")
print(f"宠物猫模型-MSE：{cat_mse:.2f},MAE:{cat_mae:.2f},R2:{cat_r2:.2f}")
print(f"宠物狗模型-MSE：{dog_mse:.2f},MAE:{dog_mae:.2f},R2:{dog_r2:.2f}")

# 输出未来预测结果
print("\n未来三年宠物数量预测：")
for year, cat_pred, dog_pred in zip(future_years, cat_predictions, dog_predictions):
    print(f"年份{year}:预测宠物猫数量：{cat_pred:.2f}万只，预测宠物狗数量：{dog_pred:.2f}万只")

# 将图形可视化
sns.set_theme(style='whitegrid')


def plot_actual_vs_predicted(years, actual, predicted, title):
    plt.figure(figsize=(12, 6))
    plt.plot(years, actual, label='Actual', marker='o')
    plt.plot(years, predicted, label='Predicted', marker='s')
    plt.title('Comparison of Dogs actual and forecasted results')
    plt.xlabel('Year')
    plt.ylabel('Number of Pets(in 10.000s)')
    plt.legend()
    plt.grid(True)
    plt.show()


plot_actual_vs_predicted(df['Year'], y_cat, cat_train_pred, 'Cat_Actual vs Predicted')
plot_actual_vs_predicted(df['Year'], y_dog, dog_train_pred, 'Dog_Actual vs Predicted')
